package org.example.loadbalancer;

import org.example.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description 轮询负载均衡器
 * @author sats@jz
 * @date 2025年01月13日 14:13
 */
public class RoundRobinLoadBalancer implements LoadBalancer{
    // 当前轮询的下标
    private final AtomicInteger currentIndex = new AtomicInteger(0);
    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {

        if (serviceMetaInfoList.isEmpty()){
            return null;
        }

        // 只有一个服务不需要轮询
        int size = serviceMetaInfoList.size();
        if(size == 1){
            return serviceMetaInfoList.get(0);
        }
        int index = currentIndex.getAndIncrement() % size;

        return serviceMetaInfoList.get(index);
    }
}
